package controller

import (
	"github.com/cy77cc/hioshop/global"
	"github.com/cy77cc/hioshop/models"
	"github.com/cy77cc/hioshop/utils"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"time"
)

type UserHandler struct {
}

func (h *UserHandler) LoginByWeixin(c *gin.Context) {
	code := c.PostForm("code")
	res := utils.Result{}
	weixinResponse := &utils.WeixinResponse{}
	err := weixinResponse.GetWeixinOpenid(code, c.GetString("appid"), c.GetString("secret"))
	if err != nil || weixinResponse.OpenId == "" {
		res.ErrNo = 1
		res.ErrMsg = "获取openid失败"
		c.JSON(503, res)
		return
	}

	user := models.User{
		WeixinOpenid: weixinResponse.OpenId,
	}
	err = user.GetUserInfoByOpenId()
	// 错误时说明没有找到用户
	newUUID := uuid.New()
	if err != nil {
		user.Username = "微信用户" + newUUID.String()[:6]
		user.Password = weixinResponse.OpenId
		user.RegisterTime = time.Now()
		user.RegisterIp = 0
		user.LastLoginTime = time.Now()
		user.LastLoginIp = 0
		user.Mobile = ""
		user.WeixinOpenid = weixinResponse.OpenId
		user.Nickname = "xxxx"
		user.Avatar = "/static/images/default_avatar.png"
		global.DB.Model(&models.User{}).Create(&user)
		return
	}

}
